import vpd from '../../mixins/vpd';
//可拖拽
import VueDraggableResizable from 'vue-draggable-resizable';
// optionally import default styles
import 'vue-draggable-resizable/dist/VueDraggableResizable.css';

export default {
  mixins: [vpd],
  components: {
    VueDraggableResizable,
  },
  data() {
    return {
      sliderVal: 100,
      zoomMin: 30,
      zoomMax: 150,
      viewStyle: {
        position: 'relative'
      },
      marginToViewPort: null,
      zoomTimer: null,
      selectStageFlag: false, //是否要选择stage
      stageDrag: null,
    }
  },
  computed: {
    // 已添加的组件
    widgetStore() {
      return this.$vpd.state.widgets;
    },
    widgetList() {
      return this.widgetStore.filter(item => !item.parent);
    },

    activeElement() {
      return this.$vpd.state.activeElement;
    },
    zoom() {
      return this.$vpd.state.zoom;
    },
    pageInfo() {
      return this.$vpd.state.page;
    },
    backgroundImage() {
      if (this.pageInfo.backgroundImg) {
        return 'url("' + process.env.VUE_APP_BASE_API + this.pageInfo.backgroundImg + '")';
      }
      return null;
    },
    pageSizeChange() {
      const {width, height} = this.pageInfo;
      return {width, height};
    }
  },
  watch: {
    zoom: function (val) {
      this.sliderVal = val;
    },
    pageSizeChange: function (val) {
      this.$nextTick(() => {
        this.$refs.viewport.update();
      })
    }
  },
  mounted() {
    setTimeout(() => {
      const wrap = this.$refs.viewport.wrap;
      wrap.scrollTo(
        this.pageInfo.scrollLeft,
        this.pageInfo.scrollTop
      );
      this.$refs.viewport.update();

      wrap.onscroll = e => {
        // console.log('onscroll',e, wrap.scrollLeft, wrap.scrollTop);
        this.$vpd.commit('scroll', {
          left: wrap.scrollLeft,
          top: wrap.scrollTop,
        })
      }

    }, 600);

    //页面尺寸变化后，组件要重新计算可移动的边界
    this.$vpd.$on('pageSizeChange', () => {
      if (this.$refs.layer1VDR) {
        this.$refs.layer1VDR.forEach(item => item.checkParentSize());
      }
      if (this.$refs.layer2VDR) {
        this.$refs.layer2VDR.forEach(item => item.checkParentSize());
      }

    })

  },
  methods: {
    getChildren(parentId) {
      return this.widgetStore.filter(item => item.parent === parentId);
    },
    doZoom(val) {
      clearTimeout(this.zoomTimer);
      const wrap = this.$refs.viewport.wrap;

      const w = this.pageInfo.width;
      const h = this.pageInfo.height;
      //这个位置短时间缓存，连续缩放时保证画布位置不乱窜
      let left, top = null;
      if (this.marginToViewPort) {
        left = this.marginToViewPort.left;
        top = this.marginToViewPort.top;
      } else {
        left = wrap.scrollLeft - w * this.zoom / 100;
        top = wrap.scrollTop - h * this.zoom / 100;
        this.marginToViewPort = {
          left: left,
          top: top,
        };
      }
      //缩放后，
      left = w * val / 100 + left;
      top = h * val / 100 + top;
      wrap.scrollTo(left, top);
      this.$vpd.commit('zoom', val);
      //缩放改变，大小改变，需更新滚动条
      this.$refs.viewport.update();

      this.zoomTimer = setTimeout(() => {
        this.marginToViewPort = null;
      }, 1000)
    },
    //组件拖放后
    onComponentDrop(ev) {
      const data = ev.dataTransfer.getData('item');
      if (!data) {
        return;
      }
      const item = JSON.parse(data);
      console.log('drop item', item, ev.offsetX, ev.offsetY);
      item.setting.x = ev.offsetX;
      item.setting.y = ev.offsetY;
      //添加组件
      this.$vpd.dispatch('addWidget', item);
    },
    onDragStart(item) {
      this.$vpd.commit('dragStart', {
        uuid: item.uuid
      });
    },
    onResizeStart() {
      // console.log('onResizeStart')
    },
    onResizestop(item) {
      // console.log('onResizestop', item);
      if (item.isContainer && this.getChildren(item.uuid).length > 0) {
        //容器内的组件重新计算边界
        this.$refs.layer2VDR.forEach(item => {
          item.checkParentSize();
        })
      }
    },
    onDragstop(item) {
      // console.log('onDragstop');
    },

    onItemActivated(item) {
      // console.log('onItemActivated', item.uuid);
      // 设置选中元素
      this.$vpd.commit('select', {
        uuid: item.uuid
      });
    },
    onStageMouseDown(e) {
      this.selectStageFlag = true;
      this.stageDrag = e;
    },
    onStageSelect() {
      if (this.selectStageFlag) { //只有在舞台按下鼠标的，抬起鼠标时才当作选中舞台
        this.$vpd.commit('select', {
          uuid: -1
        });
        this.selectStageFlag = false;
      }

    },
    /**
     * 鼠标按住舞台后可以进行拖动
     * @param ev
     */
    onStageMouseMove(ev) {
      if (this.stageDrag) {
        const wrap = this.$refs.viewport.wrap;
        wrap.scrollTo(
          wrap.scrollLeft - ev.movementX,
          wrap.scrollTop - ev.movementY,
        );
      }
    },
    handleMousewheel(e) {
      let zoom = this.sliderVal;
      const speed = 3;
      if (e.wheelDelta > 0) { //放大
        zoom += speed;
      } else { //缩小
        zoom -= speed;
      }
      if (zoom > this.zoomMax) {
        zoom = this.zoomMax;
      }
      if (zoom < this.zoomMin) {
        zoom = this.zoomMin;
      }
      this.doZoom(zoom);

    },
    onItemResize(left, top, width, height) {
      this.$vpd.commit('resize', {
        x: left,
        y: top,
        w: width,
        h: height,
      });
    },
    onItemDrag(left, top) {
      this.$vpd.commit('move', {
        x: left,
        y: top,
      })
    },
    showOperList(ev, item) {
      this.$vpd.$emit('vpd-contextmenu', {
        event: ev,
        item: item
      });
      /*this.onItemActivated(item);
      this.$refs.itemOperDropdown.$el.style.left = (ev.clientX - 270) + 'px';
      this.$refs.itemOperDropdown.$el.style.top = (ev.clientY - 45) + 'px';
      this.$refs.itemOperListBtn.click();*/
    },
    /**
     * 删除元件对象
     */
    handleRemoveItem() {
      console.log('delete', this.activeElement);
      this.$vpd.commit('delete');
    },
    /**
     * 复制元件对象
     */
    handleCopyItem() {
      const setting = JSON.parse(JSON.stringify(this.activeElement));
      //复制出来的位置稍微错开一些
      setting.x += 20;
      setting.y += 20;
      const item = {setting: setting};
      this.$vpd.dispatch('addWidget', item);
    }

  }
}
